package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    private static  final String DISH_KEY="dish_";


    @Override
    @Transactional
    public void add(DishDTO dishDTO) {
        Dish  dish= new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dish.setStatus(StatusConstant.ENABLE);
        dishMapper.add(dish);
        //获取新插入的菜品的id
        Long dishId = dish.getId();
        List<DishFlavor> flavors = dishDTO.getFlavors();
        for (DishFlavor flavor : flavors) {
            //设置口味的菜品id
                flavor.setDishId(dishId);
        }
        //利用动态sql批量插入
        dishFlavorMapper.adds(flavors);
        String dishKey = DISH_KEY+dishDTO.getCategoryId();
        redisTemplate.delete(dishKey);
    }

    @Override
    public PageResult query(DishPageQueryDTO queryDTO) {
        PageHelper.startPage(queryDTO.getPage(), queryDTO.getPageSize());
        Page<DishVO> page= dishMapper.query(queryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Transactional
    @Override
    public void del(String ids) {
        String[] idArr = ids.split(",");
        List<Long> idList= new ArrayList<Long>();
        for (String idStr : idArr) {
            Long id = Long.parseLong(idStr);
            idList.add(id);
            //获取菜品状态
            int status= dishMapper.getStatusById(id);
            //判断菜品状态，如果菜品在起售状态则不能删除
            if(status==StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
            //获取菜品关联的套餐数量
            int count=setmealDishMapper.getCountBydishId(id);
            //关联的套餐数量大于0则不能删除
            if(count>0){
                throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }
        }
        //批量删除菜品
        dishMapper.del(idList);
        //批量删除菜品口味
        dishFlavorMapper.del(idList);
        //获取redis中所以以dish_*开头的key
        Set keys= redisTemplate.keys("dish_*");
        //批量删除
        redisTemplate.delete(keys);

    }

    @Override
    public DishVO getById(Long id) {
        DishVO dishVO= dishMapper.getById(id);
        List<DishFlavor> dishFlavors =dishFlavorMapper.listByDishId(id);
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }

    /*
    * 起售/禁售菜品
    * */
    @Override
    public void updateStatus(Long id, Integer status) {
        Dish dish = new Dish();
        dish.setId(id);
        dish.setStatus(status);
        dishMapper.update(dish);
        long categoryId= dishMapper.getCategoryById(id);
        String dishKey = DISH_KEY+categoryId;
        redisTemplate.delete(dishKey);
    }

    @Transactional
    @Override
    public void update(DishDTO dish) {
        Dish dish1 = new Dish();
        BeanUtils.copyProperties(dish,dish1);
        dishMapper.update(dish1);
        List<DishFlavor> flavors = dish.getFlavors();
        List<Long> list = new ArrayList<>();
        //修改菜品口味：先删除原来的数据，再重新插入新的数据
        //删除
        list.add(dish.getId());
        dishFlavorMapper.del(list);
        //插入
        if(flavors.size()>0){
            for (DishFlavor flavor : flavors) {
                //设置口味的菜品id
                flavor.setDishId(dish.getId());
            }
            dishFlavorMapper.adds(flavors);
        }
        //获取redis中所以以dish_*开头的key
        Set keys= redisTemplate.keys("dish_*");
        //批量删除
        redisTemplate.delete(keys);

    }

    @Override
    public List<Dish> listByCatehoryId(Long categoryId) {
        return dishMapper.listByCatehoryId(categoryId);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        String dishKey = DISH_KEY+dish.getCategoryId();
        List<DishVO> dishVOList = (List<DishVO>)redisTemplate.opsForValue().get(dishKey);
        if(dishVOList!=null&&dishVOList.size()>0){
            return dishVOList;
        }
        List<Dish> dishList = dishMapper.list(dish);
        dishVOList=new ArrayList<>();
        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.listByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }
        redisTemplate.opsForValue().set(dishKey, dishVOList,15, TimeUnit.DAYS);
        return dishVOList;
    }
}
